package com.recharge.web.controller;


import com.recharge.common.domain.PageDO;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.common.util.FunctionUtil;
import com.recharge.domain.query.OrderQueryDO;
import com.recharge.domain.vo.OrderDO;
import com.recharge.service.OrderService;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

	@Autowired
    private OrderService orderService;

	@Value("${file.order.template}")
	private String fileTemplatePath;

	@RequiresPermissions("order:page")
	@RequestMapping(value="/page.html", method = RequestMethod.POST)
	@ApiOperation(value="分页查询订单", notes="")
	public @ResponseBody  ObjectResponse<PageDO> page(@RequestBody OrderQueryDO query) {
	 	ObjectResponse<PageDO> response = new ObjectResponse<>();
	 	query.setMerchantId(getUserMerchantId());
	 	ResultDO result = orderService.find(query);
	 	if(result.isSuccess()) {
			response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	}

	@RequiresPermissions("order:reportorder")
	@RequestMapping(value="/reportorder.html", method = RequestMethod.POST)
	@ApiOperation(value="统计订单", notes="")
	public @ResponseBody  ObjectResponse<PageDO> reportorder(@RequestBody OrderQueryDO query) {
		ObjectResponse<PageDO> response = new ObjectResponse<>();
		query.setMerchantId(getUserMerchantId());
		ResultDO result = orderService.reportorder(query);
		if(result.isSuccess()) {
			response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("order:orderRefund")
	@RequestMapping(value="/orderRefund.html", method = RequestMethod.POST)
	@ApiOperation(value="订单退款", notes="")
	public @ResponseBody  ObjectResponse<Object> orderRefund(@RequestBody OrderDO domain) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		ResultDO result = orderService.orderRefund(domain);
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("order:callBack")
	@RequestMapping(value="/callBack.html", method = RequestMethod.POST)
	@ApiOperation(value="订单异步回调", notes="")
	public @ResponseBody  ObjectResponse<Object> callBack(@RequestBody OrderDO domain) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		ResultDO result = orderService.callBack(domain);
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("order:callBackBatch")
	@RequestMapping(value="/callBackBatch.html", method = RequestMethod.POST)
	@ApiOperation(value="批量订单异步回调", notes="")
	public @ResponseBody  ObjectResponse<Object> callBackBatch(@RequestBody OrderDO domain) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		ResultDO result = orderService.callBackBatch(domain);
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("order:download")
	@RequestMapping(value="/download.html", method = RequestMethod.POST)
	@ApiOperation(value="订单下载", notes="")
	public void download(@RequestBody OrderQueryDO query, HttpServletResponse response) {

		query.setMerchantId(getUserMerchantId());
		ResultDO result = orderService.findList(query);
		List<OrderDO> list= (List<OrderDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);

		Map map = new HashMap();
		map.put("data",list);
		map.put("fun", new FunctionUtil());
		try{
			InputStream is = new FileInputStream(fileTemplatePath);
			// 实例化 XLSTransformer 对象
			XLSTransformer xlsTransformer = new XLSTransformer();
			// 获取 Workbook ，传入 模板 和 数据
			Workbook workbook =  xlsTransformer.transformXLS(is,map);

			// 设置文件名
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("商品列表.xls" ,"UTF-8"));
			// 写出文件
			OutputStream os = new BufferedOutputStream( response.getOutputStream() );
			// 输出
			workbook.write(os);
			// 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
			is.close();
			os.flush();
			os.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
